package com.wanakiko.impldetails.enhancer;

import com.google.common.collect.Lists;
import com.wanakiko.impldetails.lock.UnsafeLock;
import lombok.Data;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MybatisEnhancer {

    private static final int size = 8192;
    public static Map<Object, Object> objectMap = new ConcurrentHashMap<>(size);
    private static final UnsafeLock unsafeLock = new UnsafeLock();

    @Data
    static class MapperScanner {
        /* 映射文件的存放位置 */
        private String mapperLocation;

        /* 扫描映射器，模拟存在大量配置的情景 */
        public List<Object> scanMapper() {
            List<Object> objects = Lists.newArrayList();
            for (int i = 0; i < size; i++) {
                objects.add(new Object());
            }
            return objects;
        }
    }

    /* 采用HashMap模拟ConcurrentHashMap的分段锁，多线程在竞争锁的同时会发生上下文切换，外加Map的扩容比较耗时 */
//    public static synchronized void put(Object object) {
//        objectMap.put(object, object);
//    }
    public static void put(Object object) {
        unsafeLock.lock();
        objectMap.put(object, object);
        unsafeLock.unlock();
    }

    public static void main(String[] args) {
        MapperScanner mapperScanner = new MapperScanner(); /* 实例化映射器扫描器 */
        mapperScanner.setMapperLocation("classpath:mapper/*.xml"); /* 传递映射文件的类路径 */
        long timeStart = System.currentTimeMillis(); /* 记录起始时间 */
        List<Object> objects = mapperScanner.scanMapper(); /* 调用模拟配置加载的方法 */
        objects.parallelStream().forEach(MybatisEnhancer::put);
//        objects.forEach(MybatisEnhancer::put);
        long timeEnd = System.currentTimeMillis(); /* 记录结束时间 */
        System.out.println(timeEnd - timeStart); /* 打印前后的时间差值 */
    }

}
